﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App.Core.Mail;
using App.Core.Extensions;
using App.Data;
using System.Text;

public partial class Pages_Admin_SendFailedMessages : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            App.Core.Mail.MailManager.SmtpHost = ConfigReader.SmtpHost;
            App.Core.Mail.MailManager.SmtpPort = ConfigReader.SmtpPort;
            BtcHousingEntities context = new BtcHousingEntities();
            var query = (from P in context.EmailMessages where !P.IsSent select P).Count();
            lblMessage.Text = String.Format("Total {0} Messages were failed to deliver", query);
        }
    }
    protected void BindPageInfo()
    {
        Page.Title = WebUtil.GetPageTitle("Send Failed Email Messages");
    }
    protected void SendMessages()
    {
        BtcHousingEntities context = new BtcHousingEntities();
        var query = from P in context.EmailMessages where !P.IsSent select P;
        int successCount = 0;
        int failedCount = 0;
        StringBuilder errors = new StringBuilder(10);
        List<EmailMessage> messages = query == null || query.Count() == 0 ? new List<EmailMessage>() : query.ToList();
        foreach (EmailMessage message in messages)
        {
            try
            {                
                App.Core.Mail.MailManager.SendMail(message.ToEmail, message.CC, message.BCC, message.FromEmail, message.Subject, message.Message);
                
                message.IsSent = true;
                message.AttemptedOn = DateTime.Now;
                context.SaveChanges();
                successCount++;
            }
            catch(Exception ex) 
            {
                errors.AppendFormat("{0}<br/><br/>", ex.Message);
                //lblMessage.Text = ex.Message;
                //lblMessage.Text += "<br/>" + ex.StackTrace;
                
                //break;
                failedCount++;
            }
        }
        if (errors.Length > 0)
            lblMessage.Text = errors.ToString();

        lblMessage.Text += String.Format("Total {0} emails sent and {1} failed", successCount, failedCount);
    }
    protected void btnSendFailedMessages_Click(object sender, EventArgs e)
    {
        SendMessages();
    }
}